

import ConfigParser
import string
import re

from NMMirror import *
from NMAction import *
from NMUtils import *

CONF_FILE="/etc/netmirror/config.cfg"


def readConfigListener():
	global CONF_FILE
	config=ConfigParser.ConfigParser()

	logger.info("Reading " + CONF_FILE)
	config.read(CONF_FILE)
	try:
		return (config.get("listener","host"),config.get("listener","port"),config.get("listener","iface_to"))
	except:
		return(None,None,None)

def readConfigMirrors():
	global CONF_FILE
	config=ConfigParser.ConfigParser()

	logger.info("Reading " + CONF_FILE)
	config.read(CONF_FILE)
	allmirrors=[]

	for section in config.sections():
		if section=="ifaces":
			for option in config.options(section):
				logger.info("Reading config for interface " + option)
				mirrors=[]
				mirrors=readIfaceConfig(option,config.get(section,option))
				if mirrors is not None:
					for m in mirrors:
						allmirrors.append(m)
	return allmirrors

'''Section: Traffic for HTTP
Reading option with value filter tcp port not 80
Reading option with value action1 forward to interface dummy0
Reading option with value action3 resend to 127.0.0.1 port 80
Reading option with value action2 write pcap file /tmp/pcapeth.file
'''

def readIfaceConfig(iface, file):
	logger.info("Reading config for "+iface+" in file "+ file)
	config=ConfigParser.ConfigParser()
	config.read(file)
	mirrors=[]

	for section in config.sections():
		print "Section: " + section
		actions=[]
		for option in config.options(section):
			if re.match("action", option):
				print "Reading action with value " + option + " : " + config.get(section,option)
				str_action=config.get(section,option)
				m=re.match("forward\s+to\s+(interface|iface)\s(?P<iface>\w+\d*)",str_action)
				if m is not None:
					actions.append(NMActionForward(m.group("iface")))

				m=re.match("resend\s+to\s+(?P<dhost>[\w\d.\-_]+)\s+port\s+(?P<dport>\d+)",str_action)
				if m is not None:
					actions.append(NMActionResend(m.group("dhost"),m.group("dport")))

				m=re.match("write\s+pcap\s+file\s+(?P<file>[^\s]+)",str_action)
				if m is not None:
					actions.append(NMActionFileWrite(m.group("file")))
		filter=config.get(section,"filter")
		mirrors.append(NMMirror(iface,filter,actions,section))

	if len(mirrors)<1:
		print "Error reading config. Review your configuration files. No settings specified for " + iface 
		exit (1)
	return mirrors

#Net Mirror (c) 2009 Pablo Rincon Crespo
